package br.com.portalecbahia.connectionservices;


import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import br.com.portalecbahia.listner.TwitterListeners;
import br.com.portalecbahia.util.PortalECBahiaUtil;

public class SynchronizeLoginTwitter extends AsyncTask<String, Void, Boolean> {
	
	private Context context;
	private TwitterListeners listeners;
	private Twitter mTwitter;
	public static SharedPreferences mPrefs;			
	public static RequestToken mReqToken;

	
	public SynchronizeLoginTwitter(Twitter mTwitter, Context context){
	
		this.context = context;
		
		this.listeners = (TwitterListeners)context;
		  // Create a new shared preference object to remember if the user has
        mPrefs = context.getSharedPreferences("twitterPrefs", context.MODE_PRIVATE);
	}
	@Override
	protected void onPreExecute() {
		
        // Load the twitter4j helper
        mTwitter = new TwitterFactory().getInstance();
        // Tell twitter4j that we want to use it with our app
        mTwitter.setOAuthConsumer(PortalECBahiaUtil.CONSUMER_KEY, PortalECBahiaUtil.CONSUMER_SECRET);
	}
	
  
    @Override
    protected void onPostExecute(Boolean result) {               
    	listeners.onSynchronizeTwitterLoginComplete(result);
    
    }

    @Override
	protected Boolean doInBackground(String... params) {
    	try {
    		
    		mReqToken = mTwitter.getOAuthRequestToken(params[0]);
    		
    		context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mReqToken.getAuthenticationURL())));

    		return true;
    	} catch (TwitterException e) {
    		return false;
    	}
	}
    
    public static void saveAccessToken(AccessToken at) {
     	String token = at.getToken();
     	String secret = at.getTokenSecret();
     	Editor editor = mPrefs.edit();
     	editor.putString(PortalECBahiaUtil.PREF_ACCESS_TOKEN, token);
     	editor.putString(PortalECBahiaUtil.PREF_ACCESS_TOKEN_SECRET, secret);
         editor.commit();
     }
	public static void disconnect() {
	
		mPrefs.edit()
		.putString(PortalECBahiaUtil.PREF_ACCESS_TOKEN, null)
		.putString(PortalECBahiaUtil.PREF_ACCESS_TOKEN_SECRET, null)
		.commit();
	}

}
